package com.cnpc.fyspcenter.sp;

import android.content.SharedPreferences;

/**
 * Created by bingju on 2017/1/5.
 */
public abstract class SharedPreference<T> {
    final T mDefaultValue;
    PreferenceFile mFile;
    final String mKey;

    protected SharedPreference(PreferenceFile file,String key,T mDefaultValue) {
        mFile = file;
        mKey = key;
        this.mDefaultValue = mDefaultValue;
    }

    public final boolean exists() {
        return mFile.open().contains(mKey);
    }
    public final T get() {
        try {
            return read(mFile.open());
        } catch (Exception e) {
            return read(null);
        }

    }

    public final String getKey() {
        return mKey;
    }
    public final void put(T value) {
        SharedPreferences sp = mFile.open();
        SharedPreferences.Editor editor = sp.edit();
        write(editor,value);
        mFile.commit(editor);

    }
    public final void clear() {
        SharedPreferences sp = mFile.open();
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        mFile.commit(editor);
    }
    public final void remove() {
        SharedPreferences sp = mFile.open();
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(mKey);
        mFile.commit(editor);
    }

    protected abstract T read(SharedPreferences sp);

    protected abstract void write(SharedPreferences.Editor editor,T value);

}
